package megatron.com.megatron;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.BitmapFactory;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;

import com.alivc.live.pusher.AlivcAudioSampleRateEnum;
import com.alivc.live.pusher.AlivcLivePushConfig;
import com.alivc.live.pusher.AlivcLivePushInfoListener;
import com.alivc.live.pusher.AlivcLivePushStats;
import com.alivc.live.pusher.AlivcLivePusher;
import com.alivc.live.pusher.AlivcPreviewOrientationEnum;
import com.alivc.live.pusher.AlivcResolutionEnum;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;

import static com.alivc.live.pusher.AlivcAudioChannelEnum.AUDIO_CHANNEL_ONE;
import static com.alivc.live.pusher.AlivcFpsEnum.FPS_10;
import static com.alivc.live.pusher.AlivcFpsEnum.FPS_8;
import static com.alivc.live.pusher.AlivcVideoEncodeGopEnum.GOP_FIVE;

public class MainActivity extends FlutterActivity {
    private static final String CHANNEL = "cn.megatron";
    public static final String ACTION_BUTTON = "intent_action";
    private AlivcLivePusher mAlivcLivePusher = null;
    public static final int CAPTURE_PERMISSION_REQUEST_CODE = 0x1123;
    private AlivcLivePushConfig mAlivcLivePushConfig;
    //    private String mUrl = "rtmp://112.125.25.99:1935/stream/12345";
    private int mCaptureVolume = 100;
    //    private AlivcResolutionEnum mDefinition = AlivcResolutionEnum.RESOLUTION_720P;
    private final String RECORDER_STOP = "stop";
    private final String RECORDER_PAUSE = "pause";
    private final String RECORDER_RESUME = "resume";
    private final String RECORDER_HOME = "come_home";
    //通知的唯一标识号。
    private int NOTIFICATION = R.string.notification_live_start;
    MethodChannel methodChannel;


    /////////////
    static NotificationManager manager;
    static NotificationCompat.Builder builder;
    private static RemoteViews mRemoteViews;
    private int i = 0;
    private int j = 0;
    private int k = 0;
    private Button btn;
    private TextView showTv;
    private ButtonBroadcastReceiver bReceiver;
    private boolean mMuteOn = false;
    String mUrl;
    int rotation;
    int screen;
    DartExecutor dartExecutor;
    /////////////

    // 返回键 不退出 app
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(false);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(false);
        super.onBackPressed();

    }

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine);

        dartExecutor = flutterEngine.getDartExecutor();
        new MethodChannel(dartExecutor, CHANNEL).setMethodCallHandler((call, result) -> {
//            Toast.makeText(this, call.method, Toast.LENGTH_SHORT).show();
            if ("oneAct".equals(call.method)) {
                result.success("successToConnect");
                mUrl = call.argument("url");
                rotation = call.argument("rotation");
                screen = call.argument("screen");

                mAlivcLivePushConfig = new AlivcLivePushConfig();

                if (mAlivcLivePushConfig.getPreviewOrientation() == AlivcPreviewOrientationEnum.ORIENTATION_LANDSCAPE_HOME_RIGHT.getOrientation() || mAlivcLivePushConfig.getPreviewOrientation() == AlivcPreviewOrientationEnum.ORIENTATION_LANDSCAPE_HOME_LEFT.getOrientation()) {
                    mAlivcLivePushConfig.setNetworkPoorPushImage(Environment.getExternalStorageDirectory().getPath() + File.separator + "alivc_resource/poor_network_land.png");
                    mAlivcLivePushConfig.setPausePushImage(Environment.getExternalStorageDirectory().getPath() + File.separator + "alivc_resource/background_push_land.png");
                } else {
                    mAlivcLivePushConfig.setNetworkPoorPushImage(Environment.getExternalStorageDirectory().getPath() + File.separator + "alivc_resource/poor_network.png");
                    mAlivcLivePushConfig.setPausePushImage(Environment.getExternalStorageDirectory().getPath() + File.separator + "alivc_resource/background_push.png");
                }


                AlivcLivePushConfig.setMediaProjectionPermissionResultData(null);

                Common.copyAsset(this);
                Common.copyAll(this);

                if (mAlivcLivePusher == null) {
                    if (FloatWindowManager.getInstance().applyFloatWindow(MainActivity.this)) {
                        startScreenCapture();
                    }
                }

            } else if ("onStop".equals(call.method)) {
                Intent intentService = new Intent(this, MyService.class);
                stopService(intentService);
                stopPushWithoutSurface();

            }
        });
        methodChannel = new MethodChannel(dartExecutor, CHANNEL);
        //////////////////
        manager = (NotificationManager) getBaseContext().getSystemService(getBaseContext().NOTIFICATION_SERVICE);
        //注册按键广播接收者
        initBttonReceiver();
    }


    @Override
    protected void onStart() {
        Log.i("11111", "onStart");
        super.onStart();
        if (!isHome()) {
            VideoRecordViewManager.hideViewRecordWindow();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i("11111", "onPause");
        VideoRecordViewManager.refreshFloatWindowPosition();
        Intent intentService = new Intent(this, MyService.class);
        startService(intentService);
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i("11111", "onStop");
        if (isHome()) {
            if (mAlivcLivePusher != null && mAlivcLivePusher.isPushing()) {
                VideoRecordViewManager.createViewoRecordWindow(MainActivity.this, getApplicationContext(), mAlivcLivePusher, cameraOnListener);
                VideoRecordViewManager.showViewRecordWindow();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i("11111", "onResume");
    }

    private VideoRecordViewManager.CameraOn cameraOnListener = new VideoRecordViewManager.CameraOn() {
        @Override
        public void onCameraOn(boolean on) {
            if (on) {
                VideoRecordViewManager.createViewoRecordCameraWindow(MainActivity.this, getApplicationContext(), mAlivcLivePusher);
            } else {
                VideoRecordViewManager.removeVideoRecordCameraWindow(getApplicationContext());
            }
        }
    };

    private boolean isHome() {
        ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
        return getHomes().contains(rti.get(0).topActivity.getPackageName());
    }

    private List<String> getHomes() {
        List<String> names = new ArrayList<>();
        PackageManager packageManager = this.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo ri : resolveInfos) {
            names.add(ri.activityInfo.packageName);
        }
        return names;
    }


    @TargetApi(21)
    private void startScreenCapture() {
        if (Build.VERSION.SDK_INT >= 21) {
            MediaProjectionManager mediaProjectionManager = (MediaProjectionManager)
                    getApplication().getSystemService(Context.MEDIA_PROJECTION_SERVICE);
            try {
                this.startActivityForResult(
                        mediaProjectionManager.createScreenCaptureIntent(), CAPTURE_PERMISSION_REQUEST_CODE);
            } catch (ActivityNotFoundException ex) {
                ex.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext()
                                , "Start ScreenRecording failed, current device is NOT suuported!", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        } else {
            Toast.makeText(this, "视频传送需要5.0版本以上", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CAPTURE_PERMISSION_REQUEST_CODE: {
                if (resultCode == Activity.RESULT_OK) {
                    mAlivcLivePushConfig.setMediaProjectionPermissionResultData(data);
                    if (mAlivcLivePushConfig.getMediaProjectionPermissionResultData() != null) {
                        if (mAlivcLivePusher == null) {
                            startPushWithoutSurface(mUrl);

                        } else {
                            stopPushWithoutSurface();
                        }
                    }
                }
            }
            break;
        }
    }

    private void startPushWithoutSurface(String url) {
        mAlivcLivePusher = new AlivcLivePusher();

        mAlivcLivePushConfig.setTargetVideoBitrate(1400);//目标码率
        mAlivcLivePushConfig.setMinVideoBitrate(400);//最小码率
        mAlivcLivePushConfig.setInitialVideoBitrate(800);//初始码率
        mAlivcLivePushConfig.setAudioBitRate(6400);//音频码率
        mAlivcLivePushConfig.setMinFps(FPS_8);//最小帧率
        mAlivcLivePushConfig.setFps(FPS_10);//采集帧率
        mAlivcLivePushConfig.setAudioSamepleRate(AlivcAudioSampleRateEnum.AUDIO_SAMPLE_RATE_16000);//音频采样
        mAlivcLivePushConfig.setAudioChannels(AUDIO_CHANNEL_ONE);
        mAlivcLivePushConfig.setVideoEncodeGop(GOP_FIVE);

        if (0 == rotation) {
            mAlivcLivePushConfig.setPreviewOrientation(AlivcPreviewOrientationEnum.ORIENTATION_PORTRAIT);
        } else if (1 == rotation) {
            mAlivcLivePushConfig.setPreviewOrientation(AlivcPreviewOrientationEnum.ORIENTATION_LANDSCAPE_HOME_LEFT);
        } else if (2 == rotation) {
            mAlivcLivePushConfig.setPreviewOrientation(AlivcPreviewOrientationEnum.ORIENTATION_LANDSCAPE_HOME_RIGHT);
        }
        if (0 == screen) {
            mAlivcLivePushConfig.setResolution(AlivcResolutionEnum.RESOLUTION_540P);
        } else if (1 == screen) {
            mAlivcLivePushConfig.setResolution(AlivcResolutionEnum.RESOLUTION_720P);
        }


        try {
            mAlivcLivePusher.init(getApplicationContext(), mAlivcLivePushConfig);
        } catch (Exception e) {
            e.printStackTrace();
        }

        mAlivcLivePusher.setLivePushInfoListener(new AlivcLivePushInfoListener() {
            @Override
            public void onPreviewStarted(AlivcLivePusher pusher) {

            }

            @Override
            public void onPreviewStoped(AlivcLivePusher pusher) {

            }

            @Override
            public void onPushStarted(AlivcLivePusher pusher) {
            }

            @Override
            public void onFirstAVFramePushed(AlivcLivePusher pusher) {
            }

            @Override
            public void onPushPauesed(AlivcLivePusher pusher) {

            }

            @Override
            public void onPushResumed(AlivcLivePusher pusher) {

            }

            @Override
            public void onPushStoped(AlivcLivePusher pusher) {

            }

            @Override
            public void onPushRestarted(AlivcLivePusher pusher) {

            }

            @Override
            public void onFirstFramePreviewed(AlivcLivePusher pusher) {

            }

            @Override
            public void onDropFrame(AlivcLivePusher pusher, int countBef, int countAft) {

            }

            @Override
            public void onAdjustBitRate(AlivcLivePusher pusher, int curBr, int targetBr) {

            }

            @Override
            public void onAdjustFps(AlivcLivePusher pusher, int curFps, int targetFps) {

            }
        });

        mAlivcLivePusher.startPreview(null);
        mAlivcLivePusher.startPush(url);

        // flutter 通信
        methodChannel.invokeMethod("android", "onStart");

        //binaryMessenger在实际开发过程中传递flutterView对象就ok了
        mAlivcLivePusher.setCaptureVolume(mCaptureVolume);
        showNotifictionIcon(getBaseContext());

        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }

    //
    private void stopPushWithoutSurface() {
        VideoRecordViewManager.removeVideoRecordCameraWindow(getApplicationContext());
        VideoRecordViewManager.removeVideoRecordWindow(getApplicationContext());
        if (mAlivcLivePusher != null) {
            try {
                mAlivcLivePusher.stopCamera();
                mAlivcLivePusher.stopCameraMix();
                mAlivcLivePusher.stopPush();
                mAlivcLivePusher.stopPreview();
                mAlivcLivePusher.destroy();
            } catch (Exception e) {
            }
            mAlivcLivePusher.setLivePushInfoListener(null);
            mAlivcLivePusher = null;
        }
        manager.cancelAll();// 隐藏通知
        methodChannel.invokeMethod("android", "onStop");
    }


    @Override
    protected void onDestroy() {
        VideoRecordViewManager.removeVideoRecordCameraWindow(getApplicationContext());
        VideoRecordViewManager.removeVideoRecordWindow(getApplicationContext());
        if (mAlivcLivePusher != null) {
            try {
                mAlivcLivePusher.stopCamera();
                mAlivcLivePusher.stopCameraMix();
                mAlivcLivePusher.stopPush();
                mAlivcLivePusher.stopPreview();
            } catch (Exception e) {
            }
            mAlivcLivePusher.destroy();
            mAlivcLivePusher.setLivePushInfoListener(null);
            mAlivcLivePusher = null;
        }
        super.onDestroy();
    }


    //消息通知设置和显示
    public static void showNotifictionIcon(Context context) {
        builder = new NotificationCompat.Builder(context);
        mRemoteViews = new RemoteViews(context.getPackageName(), R.layout.record_menu2);


//        mRemoteViews.setImageViewBitmap(R.id.record_mic_icon,
//                BitmapFactory.decodeResource(context.getResources(), R.mipmap.status_bar_microphone));
        mRemoteViews.setImageViewResource(R.id.record_mic_icon, R.mipmap.status_bar_microphone_closed);
        mRemoteViews.setImageViewResource(R.id.record_status_icon, R.mipmap.status_bar_suspend);

        //将要跳转的界面
        Intent intent = new Intent(context, MainActivity.class);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        //activity启动模式为：singleTop
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);


        builder.setAutoCancel(false);//点击是否后消失
        builder.setSmallIcon(R.mipmap.login_logo);//设置通知栏消息标题的头像
        builder.setDefaults(NotificationCompat.DEFAULT_SOUND);//设置通知铃声
        builder.setTicker("通知");
        builder.setContentTitle("通知");
        builder.setOngoing(true);


        Intent buttonIntent = new Intent(ACTION_BUTTON);
        buttonIntent.putExtra("ButtonId", 1);
        //假如在同一个requestCode下，使用FLAG_UPDATE_CURRENT，最新接收的广播消息中的Intent的extra会替换掉旧的广播消息Intent的extra
        PendingIntent intent_btn = PendingIntent.getBroadcast(context, 1, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mRemoteViews.setOnClickPendingIntent(R.id.imageView, intent_btn);

        buttonIntent.putExtra("ButtonId", 2);
        intent_btn = PendingIntent.getBroadcast(context, 2, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mRemoteViews.setOnClickPendingIntent(R.id.record_status, intent_btn);

        buttonIntent.putExtra("ButtonId", 3);
        intent_btn = PendingIntent.getBroadcast(context, 3, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mRemoteViews.setOnClickPendingIntent(R.id.record_mic, intent_btn);
        //利用PendingIntent来包装我们的intent对象,使其延迟跳转
        builder.setContent(mRemoteViews);
        //假如在同一个requestCode下，使用FLAG_CANCEL_CURRENT，会把旧的广播消息Intent 中的extra清除掉
        PendingIntent intentPend = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        builder.setContentIntent(intentPend);

        //刷新通知
        manager.notify(0, builder.build());
    }


    //初始化广播接收器
    public void initBttonReceiver() {
        bReceiver = new ButtonBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_BUTTON);
        registerReceiver(bReceiver, intentFilter);
    }


    //广播接收类
    public class ButtonBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_BUTTON)) {
                int buttonId = intent.getIntExtra("ButtonId", 0);
                switch (buttonId) {
                    case 1:
                        break;
//                    case 2:
////                        pintLog("stop");
//                        stopPushWithoutSurface();
//                        if (bReceiver != null) {
//                            unregisterReceiver(bReceiver);
//                            bReceiver = null;
//                        }
//                        manager.cancel(0);
//                        android.os.Process.killProcess(android.os.Process.myPid());
//                        System.exit(0);
//                        break;
                    case 2:
                        if (mAlivcLivePusher != null) {
                            VideoRecordViewManager.setTimeRun();
                            AlivcLivePushStats status = mAlivcLivePusher.getCurrentStatus();
                            if (status == AlivcLivePushStats.PUSHED) {
                                mAlivcLivePusher.pause();
                                mAlivcLivePusher.setMute(true);
                                mRemoteViews.setTextViewText(R.id.record_status_text, "继续");
                                mRemoteViews.setImageViewResource(R.id.record_status_icon, R.mipmap.status_bar_continue);
                            } else if (status == AlivcLivePushStats.PAUSED) {
                                mAlivcLivePusher.resume();
                                mAlivcLivePusher.setMute(mMuteOn);
                                mRemoteViews.setTextViewText(R.id.record_status_text, "暂停");
                                mRemoteViews.setImageViewResource(R.id.record_status_icon, R.mipmap.status_bar_suspend);

                            }

                        }
                        //刷新通知
                        manager.notify(0, builder.build());
                        break;
//                    case 4:
//                        pintLog("resume");
//                        mAlivcLivePusher.resume();
//                        mAlivcLivePusher.setMute(false);
//                        mRemoteViews.setImageViewResource(R.id.record_menu_continue, R.mipmap.status_bar_suspend);
//                        mRemoteViews.setTextViewText(R.id.record_menu_status, "视频传送继续");
//                        mRemoteViews.setTextViewText(R.id.record_menu_continue_text, "继续");
//                        //刷新通知
//                        manager.notify(0, builder.build());
//                        break;
                    case 3:
                        if (mAlivcLivePusher != null) {
                            mMuteOn = !mMuteOn;
                            try {
                                mAlivcLivePusher.setMute(mMuteOn);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            if (mMuteOn) {
                                mRemoteViews.setImageViewBitmap(R.id.record_mic_icon,
                                        BitmapFactory.decodeResource(getResources(), R.mipmap.status_bar_microphone));
                                mRemoteViews.setTextViewText(R.id.record_mic_text, "打开麦克风");
                            } else {
                                mRemoteViews.setImageViewBitmap(R.id.record_mic_icon,
                                        BitmapFactory.decodeResource(getResources(), R.mipmap.status_bar_microphone_closed));
                                mRemoteViews.setTextViewText(R.id.record_mic_text, "关闭麦克风");
                            }
                            manager.notify(0, builder.build());
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }


}
